package com.hzit.mmcb.auth.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.hzit.mmcb.auth.entity.Student;
import com.hzit.mmcb.auth.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-08-28
 */
@RestController
@RequestMapping("/student")
public class StudentController extends AnalysisEventListener<Student> {
    private final Integer SIZE=10;
    List<Student> list=new ArrayList<>();
    @Autowired
    private IStudentService iStudentService;

    @GetMapping("list")
    public void list(){
        //数据
        List<Student> list = iStudentService.list();

        //写入的文件
        File file=new File("D:/student.xlsx");
        //写入操作
        EasyExcel.write(file,Student.class).sheet("学生信息列表").doWrite(list);
    }


    @GetMapping("mysql")
    public void mm(){
        File file=new File("D:/student.xlsx");
        EasyExcel.read(file,Student.class,this).sheet().doRead();
    }


    /**
     * 查询每条数据之后执行
     * @param student
     * @param analysisContext
     */
    @Override
    public void invoke(Student student, AnalysisContext analysisContext) {

        list.add(student);

        if (list.size() >=SIZE){
            save(list);
            list.clear();
        }
    }

    private void save(List<Student> list) {
        iStudentService.saveBatch(list);
    }

    /**
     * 查询完所有数据之后执行
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        save(list);
    }


}
